package com.winit.project.task;

import com.winit.common.util.ConfigUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 单例
 */
public class DrawSqlTaskContainer {

    private DrawSqlTaskContainer() {
    }

    private static final DrawSqlTaskContainer DRAW_SQL_TASK_CONTAINER = new DrawSqlTaskContainer();

    public static DrawSqlTaskContainer getInstance() {
        return DRAW_SQL_TASK_CONTAINER;
    }

    public static ExecutorService DrawSqlTaskPool = Executors.newFixedThreadPool(Integer.parseInt(ConfigUtil.getValue("build_task_max_count")));

    private static Map<String, DrawSqlTask> taskMap = new HashMap<>();

    private static final Logger logger = LoggerFactory.getLogger(DrawSqlTaskContainer.class);

    public void addTask(DrawSqlTask task) throws Exception {
        String integrationId = task.getIntegrationId();
        if (this.taskMap.containsKey(integrationId)) {
            logger.error("com.winit.project.task.DrawSqlTaskContainer.addTask.integrationId=" + integrationId);
            throw new Exception("DrawSqlTaskContainer:添加任务,正在执行中.integrationId=" + integrationId);
        }
        this.taskMap.put(integrationId, task);
        this.DrawSqlTaskPool.submit(task);
    }

    public void removeTask(String integrationId) {
        logger.info("com.winit.project.task.DrawSqlTaskContainer.removeTask.integrationId=" + integrationId);
        if (!this.taskMap.containsKey(integrationId)) {
            logger.info("com.winit.project.task.DrawSqlTaskContainer.removeTask,对象不存在.integrationId=" + integrationId);
            return;
        }
        this.taskMap.remove(integrationId);
    }
}
